// pages/function_test/dial_operate/dial_add_dial/index.ts
// import { PackResFormat, Uint8ArrayToString } from "../../../../jl_lib/jl_packResFormat_1.0.0";
import { PackResFormat, Uint8ArrayToString } from "../../../../jl_lib/jl_packResFormat_1.0.0";
import { RCSPOpSystemInfo, RCSPOpWatchDial } from "../../../../lib/rcsp-impl/rcsp";
import { OPDirectoryBrowse, OPLargerFileTrans } from "../../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        fileName: '',
        fileInfo: '',
        fileStatus: 0,//0：未读取，1：读取中，2：已读取
        transferProgressText: '',
        isTransfering: false
    },
    dialData: Uint8Array.prototype,
    lastModifyTime: 0,
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        // RCSPOpWatchDial
    },
    onUnload(){ 
        RCSPOpWatchDial?.cancelAddWatchResourseFile() 
    }, 
    /**
    * 点击事件--输入文件名
    */
    inputFileNmae(e: any) {
        var value = e.detail.value
        console.log(" tas " + value);
        this.setData({
            fileName: value
        })
    },
    /**
    * 点击事件--读取表盘文件
    */
    clickReadDialFile() {
        if (this.data.isTransfering) { 
            return 
        } 
        wx.chooseMessageFile({
            count: 1,
            success: (res) => {
                const tempFilePaths = res.tempFiles
                console.log("tempFilePaths : ", tempFilePaths);
                this.setData({
                    fileStatus: 1
                    // filePath: tempFilePaths[0].path
                })
                const fs = wx.getFileSystemManager()
                fs.getFileInfo({
                    filePath: tempFilePaths[0].path,
                    success: (res) => {
                        let fd = fs.openSync({
                            filePath: tempFilePaths[0].path
                        })
                        let uint8 = new Uint8Array(res.size);
                        fs.read({
                            fd: fd,
                            arrayBuffer: uint8.buffer,
                            length: res.size,
                            success: (_res) => {
                                this.lastModifyTime = tempFilePaths[0].time
                                this.dialData = uint8
                                console.log("读取文件成功", uint8);
                                const packResFormat = new PackResFormat()
                                const fileName = tempFilePaths[0].name
                                const fileInfoData = packResFormat.getFileData(uint8, fileName + '.json')
                                if (fileInfoData == undefined) {
                                    this.setData({
                                        fileStatus: 0,
                                        fileName: '',
                                        fileInfo: ''
                                    })
                                    wx.showToast({ title: "获取文件信息失败", icon: "error" })
                                } else {
                                    const fileInfo = Uint8ArrayToString(fileInfoData)
                                    this.setData({
                                        fileStatus: 2,
                                        fileName: fileName,
                                        fileInfo: fileInfo
                                    })
                                }
                            }, complete: (_res) => {
                                fs.close({ fd })
                            }
                        })
                    }
                })

            }
        })
    },
    /**
    * 点击事件--开始传输
    */
    clickStartTransferDialFile() {
        const fileName = this.data.fileName.trim()
        if (fileName.length == 0) {
            wx.showToast({ title: "文件名不能为空", icon: 'error' })
            return
        }
        RCSPOpSystemInfo?.getSystemInfo().then((systemInfo) => {
            if (systemInfo.callStatus == 1) {//手表通话中
                wx.showToast({
                    title: '通话中，不可操作',
                    icon: 'none'
                })
            } else if (systemInfo.callStatus == 0) {//手表空闲
                if (this.data.fileStatus == 2 && this.dialData.length > 0) {
                    const _callback: OPLargerFileTrans.TransferTaskCallback = {
                        onError: (code: number) => {
                            this.setData({
                                transferProgressText: "传输失败，code:" + code
                            })
                        },
                        onStart: () => {
                            this.setData({
                                transferProgressText: "开始传输",
                                isTransfering: true
                            })
                        },
                        onProgress: (progress: number) => {
                            this.setData({
                                transferProgressText: "正在传输，进度:" + progress
                            })
                        },
                        onSuccess: () => {
                            this.setData({
                                transferProgressText: "传输成功",
                                isTransfering: false
                            })
                        },
                        onCancel: (_code: number) => {
                            this.setData({
                                transferProgressText: "传输取消",
                                isTransfering: false
                            })
                        }
                    }
                    RCSPOpWatchDial?.addWatchResourseFile(this.dialData, fileName, this.lastModifyTime, true, _callback).then((res) => {
                        if (res instanceof OPDirectoryBrowse.File) {//传输成功且刷新目录
                            //设置为当前表盘
                            RCSPOpWatchDial?.setUsingDial(res)
                        } else if (res == undefined) {//传输完成后,目录浏览找不到该文件
                            console.error("传输完成后找不到该文件，可能是文件名不符合标准，太长或者带中文");
                        } else {//传输成功且不刷新目录
                            console.log("目录浏览的相对路径：path：" + res);
                        }
                    }).catch((error) => {
                        wx.showToast({ title: "添加表盘失败，" + error, icon: 'error' })
                    })
                } else {
                    wx.showToast({ title: "请先读取表盘文件", icon: 'error' })
                    return
                }
            }
        })


        // RCSPOpLargeFileTransfer?.cancelTransfer()

        // const callback: TransferTaskCallback = {
        //     onError: (code) => {
        //         this.setData({
        //             transferContent: "传输失败,code:" + code
        //         })
        //     }, onStart: () => {
        //         this.setData({
        //             transferContent: "传输开始:"
        //         })
        //     }, onProgress: (progress) => {
        //         this.setData({
        //             transferContent: "传输进度:" + progress
        //         })
        //     }, onCancel: (code) => {
        //         this.setData({
        //             transferContent: "传输任务取消:" + (code == 0?"App取消":"设备取消")
        //         })
        //     },onSuccess:()=>{
        //         this.setData({
        //             transferContent: "传输完成"
        //         })
        //     }
        // }
        // let fileName = tempFilePaths[0].name
        // if (this.data.fileName!=undefined) {
        //     //@ts-ignore
        //     fileName = this.data.fileName
        // }
        // RCSPOpLargeFileTransfer?.excuteTransferTask({
        //     fileBuffer: uint8,
        //     sdCardBean: this.sdCardBean,
        //     isSupportPackageCrc16: true,
        //     fileName: fileName,
        //     lastModifyTime: tempFilePaths[0].time,
        //     fileNameEncodeFormat: 0,
        //     callback
        // })
    },
    /**
    * 点击事件--取消传输
    */
    clickCancelTransferDialFile() {
        RCSPOpWatchDial?.cancelAddWatchResourseFile()
    }
})